import json

from pydantic import BaseModel, create_model
from typing import List, Tuple, Any, Optional


class DynamicModelGenerator:
    def __init__(self, config_file: str):
        self.template = self.load_template(config_file)

    def load_template(self, config_file: str) -> List[Tuple[str, str, str, str]]:
        """从配置文件加载三元组模板"""
        with open(config_file, 'r', encoding='utf-8') as file:
            data = json.load(file)
        return [(item['name'], item['remark'], item['type'], item['description']) for item in data]

    def generate_model(self) -> Any:
        """根据加载的模板生成 Pydantic 模型"""
        fields = {}

        for field_name, _, field_type, _ in self.template:
            if field_type == 'int':
                fields[field_name] = (Optional[int], None)  # 可选字段
            elif field_type == 'float':
                fields[field_name] = (Optional[float], None)  # 可选字段
            elif field_type == 'str':
                fields[field_name] = (Optional[str], None)  # 可选字段
            elif field_type == 'bool':
                fields[field_name] = (Optional[bool], None)  # 可选字段

        model = create_model('DynamicModel', **fields)
        return model

